#include "DBMaster.h"
#include<iostream>
#include"dbconnect/DBDao.h"
#include"dbconnect/Model.h"

DBMaster::DBMaster()
{
}

DBMaster::DBMaster(const std::string& host, const std::string& username, const std::string& passwd, const std::string& dbname)
{
	m_host = host;
	m_username = username;
	m_passwd = passwd;
	m_dbname = dbname;
	//initConnect();
}

DBMaster::~DBMaster()
{
	
	for (auto var : m_globalIds)
	{

	}
	mysql_close(m_sqlCon);
	m_sqlCon = nullptr;
}

void DBMaster::initConnect()
{
	m_sqlCon = mysql_init(0);
	MYSQL* con = mysql_real_connect(m_sqlCon, m_host.c_str(), m_username.c_str(),
		m_passwd.c_str(), m_dbname.c_str(), m_port, NULL, 0);
	auto error12 = mysql_error(m_sqlCon);
	std::cout << m_username << std::endl;
	std::cout << m_passwd << std::endl;
	std::cout << error12 << std::endl;
	if (con != NULL)
	{
		queryModelGlobalId();
	}
}

void DBMaster::queryModelGlobalId()
{
	DBModel::Modelglobalid mod;
	DBDao<DBModel::Modelglobalid>  dao(m_sqlCon);
	dao.setModel(mod);
	auto list = dao.queryModel();
	for(auto var:list)
	{
		m_globalIds[var.idmodelGlobalId] = var.globalId;
	}
}

MYSQL* DBMaster::getSqlConnnect()
{
	return m_sqlCon;
}

int64_t DBMaster::getBlobalId(const std::string& name)
{
	auto iter = m_globalIds.find(name);
	if (iter != m_globalIds.end())
	{
		auto id = iter->second;
		DBModel::Modelglobalid mod;
		DBDao<DBModel::Modelglobalid>  dao(m_sqlCon);
		mod.idmodelGlobalId = name;
		mod.globalId = id + 1;
		dao.setModel(mod);
		if (dao.updateModel("idmodelGlobalId", name))
		{
			return iter->second++;
		}
		return 0;
	}
	return 0;
}
